import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/index.js'
import { showToast } from 'vant'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      component: () => import('@/views/Login/index.vue')
    },
    {
      path: '/layout',
      component: () => import('@/views/Tabbar/index.vue'),
      children: [
        {
          path: '/home',
          component: () => import('@/views/Tabbar/second/HomePage.vue')
        },
        {
          path: '/category',
          component: () => import('@/views/Tabbar/second/Category.vue')
        },
        {
          path: '/shoppingCart',
          meta: {
            keepAlive: true //设置页面是否需要使用缓存
          },
          component: () => import('@/views/Tabbar/second/ShoppingCart.vue')
        },
        {
          path: '/user',
          component: () => import('@/views/Tabbar/second/User.vue')
        }
      ]
    },
    {
      path: '/address',
      component: () => import('@/views/Address/index.vue')
    },
    {
      path: '/address/:mode',
      component: () => import('@/views/Address/AddOrUpdateForm/index.vue')
    },
    {
      path: '/search',
      component: () => import('@/views/Search/index.vue')
    },
    {
      path: '/searchList/:categoryId?',
      component: () => import('@/views/SearchList/index.vue')
    },
    {
      path: '/pay',
      component: () => import('@/views/Pay/index.vue')
    },
    {
      path: '/order',
      component: () => import('@/views/Order/index.vue')
    },
    {
      path: '/goodsDetail/:id?',
      component: () => import('@/views/GoodsDetail/index.vue')
    },
    {
      path: '/',
      redirect: '/home'
    },
    {
      path: '/:pathMatch(.*)*',
      component: () => import('@/views/404/index.vue')
    }
  ]
})

// 前置守卫 拦截未登录用户
router.beforeEach((to) => {
  const checkArea = ['/pay', '/order', '/address']
  // 如果未登录要访问 支付页 或 订单页 地址 重定向登录页
  const userStore = useUserStore()
  if (
    (checkArea.includes(to.path) || to.path.includes('/address')) &&
    !userStore.token
  ) {
    showToast('请先登录')
    return '/login'
  }
  // 返回undine 或 true 即放行
})

export default router
